#include "KnowledgeBase.h"

namespace xpm {
	KnowledgeBase::KnowledgeBase(){
		_rootClses = new Cls("THING", 0);
	}
	KnowledgeBase::~KnowledgeBase() {
		clear();
	}	
	Cls* KnowledgeBase::getRootClses() {
		return _rootClses;
	}
	ClsesMap& KnowledgeBase::clses() {
		return _clses;
	}
	SlotsMap& KnowledgeBase::slots() {
		return _slots;
	}
	InstancesMap& KnowledgeBase::instances() {
		return _instances;
	}
	Cls* KnowledgeBase::createCls(string clsName, Cls* superCls) {
		Cls* cls = new Cls(clsName, superCls);
		_clses[clsName] = cls;
		return cls;
	}
	Slot* KnowledgeBase::createSlot(string slotName) {
		Slot* slot = new Slot(slotName);
		_slots[slotName] = slot;
		return slot;
	}
	Instance* KnowledgeBase::createInstance(string instanceName, Cls* cls) {
		Instance* instance = new Instance(instanceName, cls);
		_instances[instanceName] = instance;
		return instance;
	}
	void KnowledgeBase::removeCls(Cls* cls) {
		if(cls) {
			ClsesIter it =  _clses.find(cls->name());
			_clses.erase(it);
			delete cls;
			cls = 0;
		}
	}
	void KnowledgeBase::removeSlot(Slot* slot) {
		if(slot) {
			SlotsIter it = _slots.find(slot->name());
			_slots.erase(it);
			delete slot;
			slot = 0;
		}
	}
	void KnowledgeBase::removeInstance(Instance* instance) {
		if(instance) {
			InstancesIter it = _instances.find(instance->name());
			_instances.erase(it);
			delete instance;
			instance = 0;
		}
	}
	Cls* KnowledgeBase::findCls(string clsName) {
		ClsesIter it = _clses.find(clsName);
		if(it != _clses.end())
			return it->second;
		else
			return 0;
	}
	Slot* KnowledgeBase::findSlot(string slotName) {
		SlotsIter it = _slots.find(slotName);
		if(it != _slots.end())
			return it->second;
		else
			return 0;
	}
	Instance* KnowledgeBase::findInstance(string instanceName) {
		InstancesIter it = _instances.find(instanceName);
		if(it != _instances.end())
			return it->second;
		else
			return 0;
	}
	void KnowledgeBase::clear() {
		delete _rootClses;
		_rootClses = 0;
		for(ClsesIter it = _clses.begin(); it != _clses.end(); ++it) {
			delete it->second;
			it->second = 0;
		}
		_clses.clear();
		for(SlotsIter it = _slots.begin(); it != _slots.end(); ++it) {
			delete it->second;
			it->second = 0;
		}
		_slots.clear();
		for(InstancesIter it = _instances.begin(); it != _instances.end(); ++it) {
			delete it->second;
			it->second = 0;
		}
		_instances.clear();
	}
}